package com.android.accessibility.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import com.google.gson.annotations.SerializedName;

public class Printable {

    public static String toString(Object logObj) {
        if (logObj == null) {
            return null;
        }
        Class<?> thiz = logObj.getClass();
        if (thiz != null) {
            String out = null;
            Field[] allFields = thiz.getDeclaredFields();
            Field[] superFields = null;
            Class<?> superThiz = thiz.getSuperclass();
            if (superThiz != null) {
                superFields = superThiz.getDeclaredFields();
            }
            out = "\n++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
            out += printField(logObj, allFields);
            if (superFields != null) {
                out += printField(logObj, superFields);
            }
            out += "=====================================================";
            return out;
        }
        return logObj.toString();
    }

    private static String printField(Object obj, Field[] allFields) {
        String out = "";
        Object object = null;
        if (allFields != null) {
            String fieldName = null;
            String fieldValue = null;
            for (Field f : allFields) {
                if (Modifier.isStatic(f.getModifiers()))  {
                    continue;
                }
                f.setAccessible(true);
                fieldName = f.getName();
                try {
                    object = f.get(obj);
                    fieldValue = object != null ? object.toString() : null;
                } catch (IllegalArgumentException e) {
                    Log.d(Log.TAG, "error : " + e);
                } catch (IllegalAccessException e) {
                    Log.d(Log.TAG, "error : " + e);
                }
                out += String.format("%-30s: %s\n", fieldName, fieldValue);
                f.setAccessible(false);
            }
        }
        return out;
    }

    /**
     * 过滤那些没有SerializedName注解的字段
     * @param f
     * @return
     */
    @SuppressWarnings("unused")
    private static boolean filterAnnotation(Field f) {
        if (f == null) {
            return true;
        }
        Annotation[] aList = f.getDeclaredAnnotations();
        if (aList != null) {
            for (Annotation a : aList) {
                if (a.annotationType() == SerializedName.class) {
                    return false;
                }
            }
        }
        return true;
    }
}
